package com.lihua.phonecode.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.lihua.phonecode.service.PhoneCodeService;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 15594
 */
@RestController
public class PhoneCodeController {

    @Autowired
    private PhoneCodeService phoneCodeService;


    /**
     * 发送验证码到手机
     * */
    @SentinelResource(value = "sendCode",defaultFallback ="defaultFallback")
    @RequestMapping("/sendCode/{phone}")
    public String sendCode(@PathVariable("phone") String phone){
        String code = phoneCodeService.getRandomCode();
        boolean b = phoneCodeService.sendCode(code,phone);
        System.out.println(b);
        if (b){
            return "1";
        }else {
            return "0";
        }

    }
    /**
     * 判断验证码是否正确或者过期
     * */
    @GetMapping("/isCode/{phone}/{code}")
    @SentinelResource(value = "sendCode",defaultFallback ="defaultFallback" )
    public String isPhoneCode(@PathVariable("phone") String phone,@PathVariable("code") String code){
        System.out.println("6612222116");
        if (phoneCodeService.lockPhone(phone).equals("lock")){
            return "连续输入错误账号已冻结!";
        }
        int resultCode = phoneCodeService.isPhoneCode(code, phone);
        if (resultCode==1){
            //验证码正确
            return "1";
        }else if(resultCode==0) {
            //验证码过期
            return "0";
        }else {
            String s = phoneCodeService.lockPhone(phone);
            return "验证码错误-》！！"+s;
        }
    }
    /**
     * 返回值类型必须与原函数返回值类型一致；
     * 方法参数列表需要为空，或者可以额外多一个 Throwable 类型的参数用于接收对应的异常。
     * 为了解决代码膨胀，我们给一个默认的降级方法
     * */
    public static String defaultFallback(Throwable e){
        return e.getMessage();
    }
}
